<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-table ref="tableRef" v-loading="loading" :data="tableData" @selection-change="handleSelectionChange"
      style="width: 100%; height: 400px">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="tagName" label="标签名称"  />
      <el-table-column prop="tagNote" label="备注"  />
    </el-table>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
defineOptions({ name: 'MemberForm' })
import * as PublishApi from '@/api/publish/index'
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中:1）修改时的数据加载；2）提交的按钮禁用
const tableData = ref([])// 标签数据
const loading = ref(true) // 列表的加载中
const getData = async () => {
  loading.value = true
  try {
    const data = await PublishApi.getTagList({
      pageNo: 1,
      pageSize: 10,
    })
    tableData.value = data.records
  } finally {
    loading.value = false
  }
}

const publishId = ref()
const tableRef = ref()
// 打开弹窗
const open = async (id) => {
  dialogVisible.value = true
  dialogTitle.value = '添加标签'
  publishId.value = id
  await getData()
  const tagids = ref([])
  tagids.value = await PublishApi.getTagById(id)
  tableData.value.forEach((item) => {
    setTimeout(() => {
      if (tagids.value.includes(item.id))
        tableRef.value.toggleRowSelection(item, true)/*选中数据*/
    })
  })
}
// 提供 open 方法，用于打开弹窗
defineExpose({ open })

// 提交表单
const emit = defineEmits(['success'])
// 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 提交请求
  formLoading.value = true
  try {
    await PublishApi.addTag({
      id: publishId.value,
      tagIds: select_tag.value
    })
    message.success('添加成功')
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const select_tag = ref([]);
const multipleSelection = ref([]);
//复选框事件
const handleSelectionChange = val => {
  multipleSelection.value = val;
  // 重置
  select_tag.value = [];
  multipleSelection.value.filter(item => {
    select_tag.value.push(item.id);
  });
}
</script>
